package www.woniuxy.com.class112.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import www.woniuxy.com.class112.exception.NotLoginException;
import www.woniuxy.com.class112.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("---------登录拦截器----------");

        //1排除OPTIONS请求
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return true;
        }
        //2获取请求头中的token
        String token = request.getHeader("token");
        if (token==null){
            throw new NotLoginException();
        }
        //3如果token不为空  则进行校验
        try {
            Claims claims = JwtUtil.parseToken(token);
            //获取过期时间
            long expiredTime = claims.getExpiration().getTime();
            long currentTime = new Date().getTime();
            //提前1分钟过期
            if ((expiredTime-currentTime)/1000<60){
                throw new NotLoginException();
            }
        }catch (Exception e){
            throw new NotLoginException();
        }
        return true;
    }
}
